package iomanager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import be.kuleuven.cs.som.annotate.Basic;
import be.kuleuven.cs.som.annotate.Immutable;
import be.kuleuven.cs.som.annotate.Raw;

/**
 * This class manages the file input-output. The class supports methods for reading text files from a given path and returning
 * the corresponding String and writing Strings to a text file accompanied by a path. When an IOException occurs,
 * it is passed to the client that invoked the respective method.
 * The class uses the design pattern Singleton.
 * 
 * @author Molderez Tom, 2de bach Ingenieurswetenschappen Computerwetenschappen-Elektrotechniek and Reniers Jorn, 2de bach Ingenieurswetenschappen Werktuigkunde-Computerwetenschappen
 * @version 1.0
 *
 */
public class IOManager {
	
	/**
	 * The only object of this class.
	 */
	private static final IOManager instance = new IOManager();
	
	/**
	 * Returns the only object of this class.
	 */
	@Basic @Raw @Immutable
	public static IOManager get() {
		return instance;
	}
	
	/**
	 * Creates a new object of this class. Does nothing.
	 */
	private IOManager() {
		
	}
	
	/**
	 * Reads the text from the file with the given path and returns a String
	 * containing that text. No manipulation of the text is done.
	 * 
	 * @param path The path of which the text as String must be returned.
	 * @return A String containing the content of the text file of the given path.
	 * @throws IOException
	 * 		When some input-output exception occurs.
	 */
	public String read(String path) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(new File(path)));
		String line = null;
		StringBuffer input = new StringBuffer();
		
		try {
			while( (line = reader.readLine()) != null)
				input.append(line).append(System.getProperty("line.separator"));
			return input.toString();
		} finally {
			reader.close();
		}

	}
	
	/**
	 * Writes the given output String to a file specified by the given path.
	 * 
	 * @param path The path to where the given output String must be written.
	 * @param output The output String that must be written to a file
	 * with the given path.
	 * @post A text file with the given path and content of the output String
	 * is created in the file management system of the operating system.
	 * @throws IOException
	 * 		When some input-output exception occurs.
	 */
	public void write(String path, String output) throws IOException {
		Writer writer = new FileWriter(new File(path));
		try {
			writer.write(output);
		} finally  {
			writer.close();
		}
		
	}
	
}
